package com.lfy.fyadmin.util;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.lfy.fyadmin.entity.*;
import com.lfy.fyadmin.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 权限工具类
 */
@Component
public class PermissionUtil {
    
    @Autowired
    private UserRoleService userRoleService;
    
    @Autowired
    private RolePermissionService rolePermissionService;
    
    @Autowired
    private UserGroupService userGroupService;
    
    @Autowired
    private GroupPermissionService groupPermissionService;
    
    @Autowired
    private PermissionService permissionService;
    
    /**
     * 检查当前用户是否有指定权限
     * @param permissionCode 权限编码
     * @return 是否有权限
     */
    public boolean hasPermission(String permissionCode) {
        if (!StpUtil.isLogin()) {
            return false;
        }
        
        Long userId = StpUtil.getLoginIdAsLong();
        return hasPermission(userId, permissionCode);
    }
    
    /**
     * 检查指定用户是否有指定权限
     * @param userId 用户ID
     * @param permissionCode 权限编码
     * @return 是否有权限
     */
    public boolean hasPermission(Long userId, String permissionCode) {
        Set<String> userPermissions = getUserPermissions(userId);
        return userPermissions.contains(permissionCode);
    }
    
    /**
     * 检查当前用户是否有任意一个权限
     * @param permissionCodes 权限编码数组
     * @return 是否有权限
     */
    public boolean hasAnyPermission(String... permissionCodes) {
        if (!StpUtil.isLogin()) {
            return false;
        }
        
        Long userId = StpUtil.getLoginIdAsLong();
        Set<String> userPermissions = getUserPermissions(userId);
        
        for (String permissionCode : permissionCodes) {
            if (userPermissions.contains(permissionCode)) {
                return true;
            }
        }
        
        return false;
    }
    
    /**
     * 检查当前用户是否有所有权限
     * @param permissionCodes 权限编码数组
     * @return 是否有权限
     */
    public boolean hasAllPermissions(String... permissionCodes) {
        if (!StpUtil.isLogin()) {
            return false;
        }
        
        Long userId = StpUtil.getLoginIdAsLong();
        Set<String> userPermissions = getUserPermissions(userId);
        
        for (String permissionCode : permissionCodes) {
            if (!userPermissions.contains(permissionCode)) {
                return false;
            }
        }
        
        return true;
    }
    
    /**
     * 获取用户的所有权限编码
     * @param userId 用户ID
     * @return 权限编码集合
     */
    public Set<String> getUserPermissions(Long userId) {
        Set<Long> permissionIds = getUserPermissionIds(userId);
        
        if (CollectionUtils.isEmpty(permissionIds)) {
            return new HashSet<>();
        }
        
        List<Permission> permissions = permissionService.list(
            new LambdaQueryWrapper<Permission>()
                .in(Permission::getId, permissionIds)
                .eq(Permission::getStatus, 1)
        );
        
        return permissions.stream()
            .map(Permission::getCode)
            .collect(Collectors.toSet());
    }
    
    /**
     * 获取用户的所有权限ID
     * @param userId 用户ID
     * @return 权限ID集合
     */
    private Set<Long> getUserPermissionIds(Long userId) {
        Set<Long> permissionIds = new HashSet<>();
        
        // 1. 通过用户角色获取权限
        List<UserRole> userRoles = userRoleService.list(
            new LambdaQueryWrapper<UserRole>().eq(UserRole::getUserId, userId)
        );
        
        if (!CollectionUtils.isEmpty(userRoles)) {
            List<Long> roleIds = userRoles.stream()
                .map(UserRole::getRoleId)
                .collect(Collectors.toList());
            
            List<RolePermission> rolePermissions = rolePermissionService.list(
                new LambdaQueryWrapper<RolePermission>().in(RolePermission::getRoleId, roleIds)
            );
            
            Set<Long> rolePermissionIds = rolePermissions.stream()
                .map(RolePermission::getPermissionId)
                .collect(Collectors.toSet());
            
            permissionIds.addAll(rolePermissionIds);
        }
        
        // 2. 通过用户组获取权限
        List<UserGroup> userGroups = userGroupService.list(
            new LambdaQueryWrapper<UserGroup>().eq(UserGroup::getUserId, userId)
        );
        
        if (!CollectionUtils.isEmpty(userGroups)) {
            List<Long> groupIds = userGroups.stream()
                .map(UserGroup::getGroupId)
                .collect(Collectors.toList());
            
            List<GroupPermission> groupPermissions = groupPermissionService.list(
                new LambdaQueryWrapper<GroupPermission>().in(GroupPermission::getGroupId, groupIds)
            );
            
            Set<Long> groupPermissionIds = groupPermissions.stream()
                .map(GroupPermission::getPermissionId)
                .collect(Collectors.toSet());
            
            permissionIds.addAll(groupPermissionIds);
        }
        
        return permissionIds;
    }
}